<?php

namespace App\Services\spider;

use App\Model\CommonSpiderItem;
use App\Services\UtilService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Str;

abstract class IUrParser
{
    private IDataRepo $repo;

    public function __construct(IDataRepo $repo)
    {
        $this->repo = $repo;
    }

    /**
     * @return IDataRepo
     */
    public function getRepo(): IDataRepo
    {
        return $this->repo;
    }



    /**
     * 判断网页是否是我们需要的
     * @param string|null $url
     * @return bool
     */
    public abstract function isNeedUrl(?string $url): bool;

    /**
     *
     * 从a.src的链接获取真实的链接
     * - ?开头 eg: ?key=xx&name=x
     * - /开头 /user
     * - http,https开头
     * @param string $href a标签的src
     * @param string|null $oriUrl 网页的链接
     * @return string|null 返回过滤后的url
     */
    public abstract function filterATagHref(string $href, ?string $oriUrl): ?string;


    public function parse($url, $taskNo): HtmlResult
    {
//        $item = $this->repo->getHtmlItem($taskNo, $url);
//        if ($item) {
//            return HtmlResult::ofSuccess($item->html);
//        }
        try {
            $res = UtilService::getInstance()->http_get($url);
            if ($res->getStatusCode() == 200) {
                $content = $res->getBody()->getContents();
                return HtmlResult::ofSuccess($content);
            } else {
                return HtmlResult::ofError($res->getStatusCode());
            }
        } catch (GuzzleException $e) {
            if (Str::contains($e->getMessage(), [
                "<title>无法找到资源。</title>",
                "resulted in a `404 Not Found` response",
                "处理你的请求时出错",
                "500 Internal Server Error"
            ])) {
                return HtmlResult::ofError(CommonSpiderItem::html_code_404);
            } else {
                UtilService::getInstance()->print("get html exception,url=$url,exception:" . $e->getMessage());
            }
            return HtmlResult::ofError();
        }

    }

}